/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.func.impl;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.je.common.auth.impl.Department;
import com.je.common.auth.impl.DepartmentUser;
import com.je.common.base.DynaBean;
import com.je.common.base.func.funcPerm.fastAuth.FuncQuickPermission;
import com.je.common.base.util.SecurityUserHolder;
import com.je.meta.service.func.FuncQuickPermissionDeleteValidService;
import com.je.rbac.rpc.AccountRpcService;
import com.je.rbac.rpc.DepartmentRpcService;
import com.je.rbac.rpc.DepartmentUserRpcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FuncQuickPermissionDeleteValidServiceImpl implements FuncQuickPermissionDeleteValidService {

    @Autowired
    private AccountRpcService accountRpcService;
    @Autowired
    private DepartmentRpcService departmentRpcService;
    @Autowired
    private DepartmentUserRpcService departmentUserRpcService;

    @Override
    public boolean validDeletePermission(String funcCode, FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (funcQuickPermission == null) {
            return true;
        }

        if (!funcQuickPermission.isActive()) {
            return true;
        }

        if (SecurityUserHolder.getCurrentAccount() == null) {
            return false;
        }

        //如果有一个成功，则不执行本人更改本人校验
        boolean flag = validDeptLeaderDelete(funcQuickPermission, dynaBean)
                || validDirectLeaderDelete(funcQuickPermission, dynaBean)
                || validMonitorLeaderDelete(funcQuickPermission, dynaBean)
                || validMyDeptDelete(funcQuickPermission, dynaBean)
                || validDeptMonitroDeptDelete(funcQuickPermission, dynaBean)
                || validApprovePendingDelete(funcQuickPermission, dynaBean)
                || validApprovePendedDelete(funcQuickPermission, dynaBean)
                || validMyCompanyDelete(funcQuickPermission, dynaBean)
                || validMyGroupCompanyDelete(funcQuickPermission, dynaBean)
                || validMonitorCompanyDelete(funcQuickPermission, dynaBean)
                || validSeeUserDelete(funcQuickPermission, dynaBean)
                || validSeeDeptDelete(funcQuickPermission, dynaBean)
                || validSeeOrgDelete(funcQuickPermission, dynaBean)
                || validSeeRoleDelete(funcQuickPermission, dynaBean);

        //如果都校验不成功则校验本人更改本人
        if (!flag) {
            flag = validSelfDelete(funcQuickPermission, dynaBean);
        }

        return flag;
    }

    /**
     * 本人删除本人
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validSelfDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isMyselfDelete()) {
            return false;
        }
        if (Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountRealUserId()) || Strings.isNullOrEmpty(dynaBean.getStr(funcQuickPermission.getCreateUserIdField()))) {
            return false;
        }
        if (!SecurityUserHolder.getCurrentAccountRealUserId().equals(dynaBean.getStr(funcQuickPermission.getCreateUserIdField()))
                || !SecurityUserHolder.getCurrentAccountRealOrgId().equals(dynaBean.getStr(funcQuickPermission.getCreateDeptIdField()))) {
            return false;
        }
        return true;
    }

    /**
     * 部门领导删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validDeptLeaderDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isDeptHeadDelete()) {
            return false;
        }
        DepartmentUser departmentUser = SecurityUserHolder.getCurrentAccountRealDepartmentUser();
        if (departmentUser == null || Strings.isNullOrEmpty(dynaBean.getStr(funcQuickPermission.getCreateUserIdField()))) {
            return false;
        }

        String deptLeader = departmentRpcService.findDeptLeader(SecurityUserHolder.getCurrentAccountRealOrgId());
        if (Strings.isNullOrEmpty(deptLeader)) {
            return false;
        }

        if (!departmentUser.getId().equals(deptLeader)) {
            return false;
        }

        return true;
    }

    /**
     * 直属领导删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validDirectLeaderDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isDirectLeaderDelete()) {
            return false;
        }
        DepartmentUser departmentUser = SecurityUserHolder.getCurrentAccountRealDepartmentUser();
        if (departmentUser == null || Strings.isNullOrEmpty(dynaBean.getStr(funcQuickPermission.getCreateDeptIdField()))
                || Strings.isNullOrEmpty(dynaBean.getStr(funcQuickPermission.getCreateUserIdField()))) {
            return false;
        }

        String directLeader = departmentUserRpcService.findDirectLeaderId(dynaBean.getStr(funcQuickPermission.getCreateDeptIdField()), dynaBean.getStr(funcQuickPermission.getCreateUserIdField()));
        if (Strings.isNullOrEmpty(directLeader)) {
            return false;
        }

        if (!departmentUser.getId().equals(directLeader)) {
            return false;
        }

        return true;
    }

    /**
     * 监管领导删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validMonitorLeaderDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isMonitorLeaderDelete()) {
            return false;
        }

        DepartmentUser departmentUser = SecurityUserHolder.getCurrentAccountRealDepartmentUser();
        if (departmentUser == null || Strings.isNullOrEmpty(dynaBean.getStr(funcQuickPermission.getCreateDeptIdField()))) {
            return false;
        }

        List<String> monitDeptList = departmentUserRpcService.findMonitorDeptIds(SecurityUserHolder.getCurrentAccountRealOrgId(), SecurityUserHolder.getCurrentAccountRealUserId());
        if (monitDeptList == null || monitDeptList.isEmpty()) {
            return false;
        }

        return monitDeptList.contains(dynaBean.getStr(funcQuickPermission.getCreateDeptIdField()));
    }

    /**
     * 本部门删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validMyDeptDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isMyDeptDelete()) {
            return false;
        }
        Department department = SecurityUserHolder.getCurrentAccountDepartment();
        if (department == null || Strings.isNullOrEmpty(dynaBean.getStr(funcQuickPermission.getCreateDeptIdField()))) {
            return false;
        }
        if (!department.getId().equals(dynaBean.getStr(funcQuickPermission.getCreateDeptIdField()))) {
            return false;
        }
        return true;
    }

    /**
     * 部门监管部门删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validDeptMonitroDeptDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isDeptMonitorDeptDelete()) {
            return false;
        }

        Department department = SecurityUserHolder.getCurrentAccountDepartment();
        if (department == null || Strings.isNullOrEmpty(dynaBean.getStr(funcQuickPermission.getCreateDeptIdField()))) {
            return false;
        }

        List<String> deptMonitorDeptIdList = departmentUserRpcService.findDeptMonitorDeptIds(SecurityUserHolder.getCurrentAccountRealOrgId());
        if (deptMonitorDeptIdList == null || deptMonitorDeptIdList.isEmpty()) {
            return false;
        }

        return deptMonitorDeptIdList.contains(dynaBean.getStr(funcQuickPermission.getCreateDeptIdField()));
    }

    /**
     * 待审批删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validApprovePendingDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isApprovePendingDelete()) {
            return false;
        }
        DepartmentUser departmentUser = SecurityUserHolder.getCurrentAccountRealDepartmentUser();
        if (departmentUser == null || !dynaBean.containsKey("SY_PREAPPROVUSERS")
                || Strings.isNullOrEmpty(dynaBean.getStr("SY_PREAPPROVUSERS"))) {
            return false;
        }
        if (!Splitter.on(",").splitToList(dynaBean.getStr("SY_PREAPPROVUSERS")).contains(departmentUser.getId())) {
            return false;
        }
        return true;
    }

    /**
     * 审批后删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validApprovePendedDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isApprovePendedDelete()) {
            return false;
        }
        DepartmentUser departmentUser = SecurityUserHolder.getCurrentAccountRealDepartmentUser();
        if (departmentUser == null || !dynaBean.containsKey("SY_APPROVEDUSERS")
                || Strings.isNullOrEmpty(dynaBean.getStr("SY_APPROVEDUSERS"))) {
            return false;
        }
        if (!Splitter.on(",").splitToList(dynaBean.getStr("SY_APPROVEDUSERS")).contains(departmentUser.getId())) {
            return false;
        }
        return true;
    }

    /**
     * 公司内删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validMyCompanyDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isMyCompanyDelete()) {
            return false;
        }
        Department department = SecurityUserHolder.getCurrentAccountDepartment();
        if (department == null || Strings.isNullOrEmpty(department.getCompanyId())
                || Strings.isNullOrEmpty(dynaBean.getStr(funcQuickPermission.getCompanyIdFieldCode()))) {
            return false;
        }
        if (!department.getCompanyId().equals(dynaBean.getStr(funcQuickPermission.getCompanyIdFieldCode()))) {
            return false;
        }
        return true;
    }

    /**
     * 集团公司内删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validMyGroupCompanyDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isGroupCompanyDelete()) {
            return false;
        }
        Department department = SecurityUserHolder.getCurrentAccountDepartment();
        if (department == null || Strings.isNullOrEmpty(department.getGroupCompanyId())
                || Strings.isNullOrEmpty(dynaBean.getStr(funcQuickPermission.getGroupCompanyIdFieldCode()))) {
            return false;
        }
        if (!department.getGroupCompanyId().equals(dynaBean.getStr(funcQuickPermission.getGroupCompanyIdFieldCode()))) {
            return false;
        }
        return true;
    }

    /**
     * 监管公司内删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validMonitorCompanyDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isMonitorCompanyDelete()) {
            return false;
        }

        DepartmentUser departmentUser = SecurityUserHolder.getCurrentAccountRealDepartmentUser();
        if (departmentUser == null || Strings.isNullOrEmpty(dynaBean.getStr(funcQuickPermission.getCompanyIdFieldCode()))) {
            return false;
        }

        List<String> companyMonitorCompanyIds = departmentUserRpcService.findCompanyMonitorCompanyIds(SecurityUserHolder.getCurrentAccountDepartment().getCompanyId());
        if (companyMonitorCompanyIds == null || companyMonitorCompanyIds.isEmpty()) {
            return false;
        }

        return companyMonitorCompanyIds.contains(dynaBean.getStr(funcQuickPermission.getCompanyIdFieldCode()));
    }

    /**
     * 可见人眼删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validSeeUserDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isUserControlDelete()) {
            return false;
        }
        if (funcQuickPermission.getSeeUserIdList() == null
                || funcQuickPermission.getSeeUserIdList().isEmpty()
                || Strings.isNullOrEmpty(dynaBean.getStr(funcQuickPermission.getCreateUserIdField()))) {
            return false;
        }
        if (!funcQuickPermission.getSeeUserIdList().contains(SecurityUserHolder.getCurrentAccountRealUserId())) {
            return false;
        }
        return true;
    }

    /**
     * 可见部门删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validSeeDeptDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isDeptControlDelete()) {
            return false;
        }
        if (funcQuickPermission.getSeeDeptIdList() == null
                || funcQuickPermission.getSeeDeptIdList().isEmpty()
                || Strings.isNullOrEmpty(dynaBean.getStr("SY_CREATEORGID"))) {
            return false;
        }
        if (!funcQuickPermission.getSeeDeptIdList().contains(SecurityUserHolder.getCurrentAccountRealOrgId())) {
            return false;
        }
        return true;
    }

    /**
     * 可见机构删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validSeeOrgDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isOrgControlDelete()) {
            return false;
        }
        if (funcQuickPermission.getSeeOrgIdList() == null
                || funcQuickPermission.getSeeOrgIdList().isEmpty()
                || !dynaBean.containsKey("SY_ORG_ID")
                || Strings.isNullOrEmpty(dynaBean.getStr("SY_ORG_ID"))) {
            return false;
        }

        if (SecurityUserHolder.getCurrentAccount() == null || SecurityUserHolder.getCurrentAccount().getPlatformOrganization() == null) {
            return false;
        }

        if (!funcQuickPermission.getSeeOrgIdList().contains(SecurityUserHolder.getCurrentAccount().getPlatformOrganization().getId())) {
            return false;
        }

        return true;
    }

    /**
     * 可见角色删除
     *
     * @param funcQuickPermission
     * @param dynaBean
     * @return
     */
    private boolean validSeeRoleDelete(FuncQuickPermission funcQuickPermission, DynaBean dynaBean) {
        if (!funcQuickPermission.isRoleControlDelete()) {
            return false;
        }
        if (funcQuickPermission.getSeeRoleIdList() == null
                || funcQuickPermission.getSeeRoleIdList().isEmpty()
                || Strings.isNullOrEmpty(SecurityUserHolder.getCurrentAccountId())) {
            return false;
        }

        List<String> roleList = accountRpcService.findAccountRoleIds(SecurityUserHolder.getCurrentAccountTenantId(), SecurityUserHolder.getCurrentAccountId());
        for (String eachSeeRoleId : funcQuickPermission.getSeeRoleIdList()) {
            for (String eachAccountRoleId : roleList) {
                if (eachAccountRoleId.equals(eachSeeRoleId)) {
                    return true;
                }
            }
        }
        return false;
    }

}
